package com.mindata.blockchain.core.sql;

import com.mindata.blockchain.block.Instruction;
import com.mindata.blockchain.block.Operation;
import com.mindata.blockchain.core.event.RecoveryListEvent;
import com.mindata.blockchain.core.sqlparser.InstructionParser;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 对数据库被篡改的数据进行恢复（监听RecoveryLisEvent，根据instructionid、instruction、operation来对数据库进行相应操作）
 *
 * @Author Wong
 * @Date 2018/8/15 15:49
 */

@Component
public class RecoveryManager {

    private byte operation;

    private Instruction instruction;

    @Resource
    private InstructionParser instructionParser;

    @EventListener
    public void dbRecoveryByInstruction(RecoveryListEvent recoveryListEvent) {
        this.operation = recoveryListEvent.getOperation();
        this.instruction = recoveryListEvent.getInstruction();
        this.instruction.setOperation(operation);
        execute(instruction);
    }

    @Transactional
    public void execute(Instruction instruction) {
        doSqlParse(instruction);
    }

    private void doSqlParse(Instruction instruction) {
        instructionParser.parse(instruction);
    }
}
